from rest_framework import serializers
from goods.models import SKU


class CartSerializer(serializers.Serializer):
    """保存购物车的序列化器"""
    # sku_id, count, selected
    sku_id = serializers.IntegerField(label='商品编号', min_value=1)
    count = serializers.IntegerField(label='数量', min_value=1, max_value=5)
    selected = serializers.BooleanField(label='是否勾选', default=True)

    def validate(self, attrs):
        # 验证多个字段
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])
        except SKU.DoesNotExist:
            raise serializers.ValidationError('无此商品')
        if attrs['count'] > sku.stock:
            raise serializers.ValidationError('库存不足')
        return attrs


class CartSKUSerializer(serializers.ModelSerializer):
    """获取购物车数据的序列化器"""
    count = serializers.IntegerField(label='商品数量', min_value=1)
    selected = serializers.BooleanField(label='是否勾选')

    class Meta:
        model = SKU
        fields = ('id', 'count', 'name', 'default_image_url', 'price', 'selected')


class CartDeleteSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label='删除商品的id', min_value=1)

    def validated_sku_id(self, value):
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')
        return value


class CartSelectAllSerializer(serializers.Serializer):
    selected = serializers.BooleanField(label='全选')
